package com.superdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: SimpleRedisLock
 * Package: com.superdp.utils
 * Description:
 *
 * @Author: XKing
 * @Create: 2023/7/6 - 15:34
 * @Version: 1.0
 */
public class SimpleRedisLock implements ILock{

    //锁住userId
    private String lockUserIdName;
    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PREFIX="lock:";
    //多线程情况下，线程ID可能冲突，使用前缀避免冲突
    private static final String ID_PREFIX= UUID.randomUUID().toString(true)+"-";
    //Lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIP;

    static {
        UNLOCK_SCRIP=new DefaultRedisScript<>();
        UNLOCK_SCRIP.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIP.setResultType(Long.class);
    }

    public SimpleRedisLock(String lockUserIdName, StringRedisTemplate stringRedisTemplate) {
        this.lockUserIdName = lockUserIdName;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(Long time) {
        //获取线程表示
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + lockUserIdName,
                threadId, time, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(b);
    }

//    @Override
//    public void unLock() {
//        //查看缓存里边的线程标识和当前线程标识是否一致，如果一致说明是自己的锁，可以删除，反之不是则不删除
//        String currentId = ID_PREFIX+Thread.currentThread().getId();
//        String threadId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//        if(currentId.equals(threadId)){
//            stringRedisTemplate.delete(KEY_PREFIX+name);
//        }
//    }
    @Override
    public void unLock(){
        //执行Lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIP,
                Collections.singletonList(KEY_PREFIX+lockUserIdName),
                ID_PREFIX+Thread.currentThread().getId());
    }
}
